import axios from 'axios'
import qs from 'qs'
import { Toast } from 'vant'
// import { Loading, MessageBox } from 'element-ui'
let loadingInstance, //记录页面中存在的loading
  loadingCount = 0, //记录当前正在请求的数量
  appkey = ''
let MD5 = require('./md5')
let me = this
let zheliban = '6738c6db-69e8-11ec-a673-6805cab640a0'
let zhelibandk = '613ea0cb6f9811ed9a386805cab597a8'
let zhezhengding = '6738c85b-69e8-11ec-a673-6805cab640a0'
let zhezhengdingsk = '801ba32b6f9811ed9a386805cab597a8'
const CryptoJS = require('crypto-js')
const aesEncrypt = function (plainText) {
  var key = CryptoJS.enc.Utf8.parse(_key);
  var srcs = CryptoJS.enc.Utf8.parse(plainText);
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.toString();
};
const _key = "consmationecasof";
const aesDecrypt = function (plainText) {
  var key = CryptoJS.enc.Utf8.parse(_key);
  var decrypt = CryptoJS.AES.decrypt(plainText, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
};
axios.interceptors.request.use(
  (config) => {
    // console.log(config.headers.post['Content-Type'], 'ceshi')
    
    if (processENV.API_CONFIG == 'zlb') {
      let timestamp = Date.now()
      appkey = MD5.hex_md5(zheliban + zhelibandk + timestamp)
      config.headers.sign = appkey
      config.headers.appkey = zheliban
      config.headers.timestamp = timestamp
    } else {
      config.headers.Authorization = window.localStorage.getItem('token')
    }
    if (loadingCount == 0) {
      loadingInstance = Toast.loading({
        message: '加载中',
        duration: 0, // toast不消失
        forbidClick: true
      })
    }
    loadingCount++
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
axios.defaults.withCredentials = true
axios.interceptors.response.use(
  (response) => {
    loadingCount--

    if (loadingInstance && loadingCount == 0) {
      loadingInstance.close()
    }
    return response;
  },
  (error) => {
    loadingCount--

    if (loadingInstance && loadingCount == 0) {
      loadingInstance.close()
    }
    return Promise.resolve(error.response)
  }
)

function checkStatus(response) {
  let res = response
  if (res && res.status && res.status == 401) {
    loadingCount--

    if (loadingInstance && loadingCount == 0) {
      loadingInstance.close()
    }
    return Promise.reject('token验证错误！')
  }
  console.log(res,'hhhhhhh')
  if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
    // console.log(response,'dhjdhjhdh')  //先排除https://nfzjszlb.jst.zj.gov.cn/tyzcpt/api/rescatalog/gsaCodeCity/listForTree/330000000000这种情况
    // if(response.config.method == 'post' || (response.config.method == 'get'&&(response.config.url.split('?')[1]&&response.config.params))){
    if (response.config.headers.buried == 'encrypt') {
      if (
        typeof response.data == "string" &&
        response.data.indexOf("IsEnc") > -1) {
        response.data = JSON.parse(response.data);
        if (response.data.IsEnc && response.data.EncData) {
          let encData = eval(
            "(" + aesDecrypt(response.data.EncData) + ")"
          );
          if (typeof encData == "string") {
            encData = eval("(" + encData + ")");
          }
          response.data = encData;
        }
      } else {
        if (response.data.IsEnc && response.data.EncData) {
          let encData = eval(
            "(" + aesDecrypt(response.data.EncData) + ")"
          );
          if (typeof encData == "string") {
            encData = eval("(" + encData + ")");
          }
          response.data = encData;
        }
      }
      return response
    } else {
      return response
    }

  }
  return {
    status: -404,
    msg: res.data.msg
  }
}
function checkCode(res) {
  if (res && res.data && res.data.code === 500) {
    Message.error(res.data.msg)
    loadingCount--

    if (loadingInstance && loadingCount == 0) {
      loadingInstance.close()
    }
  }
  return res
}
function appkeyData() {
  //浙里办、浙政钉
  // 6738c6db-69e8-11ec-a673-6805cab640a0        613ea0cb6f9811ed9a386805cab597a8        浙里办
  // 6738c85b-69e8-11ec-a673-6805cab640a0        801ba32b6f9811ed9a386805cab597a8        浙政钉
  // md5(appkey + sk + timestamp)
  let MD5 = require('./md5')
  let zheliban = '6738c6db-69e8-11ec-a673-6805cab640a0'
  let zhelibandk = '613ea0cb6f9811ed9a386805cab597a8'
  let zhezhengding = '6738c85b-69e8-11ec-a673-6805cab640a0'
  let zhezhengdingsk = '801ba32b6f9811ed9a386805cab597a8'
  let timestamp = Date.now()
  appkey = MD5(zheliban + zhelibandk + timestamp)
  return appkey
}
export default {
  post(url, data) {
    return axios({
      method: 'post',
      url,
      data: qs.stringify(data),
      withCredentials: true,
      timeout: 300000,
      dataType: 'json',
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }).then((response) => {
      return checkStatus(response)
    })
  },
  get(url, params) {
    return axios({
      method: 'get',
      url,
      params,
      withCredentials: true,
      timeout: 300000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      }
    }).then((response) => {
      return checkStatus(response)
    })
  },
  getImage(url, data) {
    return axios({
      method: 'post',
      url,
      data: data,
      withCredentials: true,
      timeout: 300000,
      dataType: 'json',
      headers: {},
      responseType: 'arraybuffer'
    }).then((response) => {
      return checkStatus(response)
    })
  },
  postJson(url, data) {
    return axios({
      method: 'post',
      url,
      data: data,
      withCredentials: true,
      timeout: 300000,
      dataType: 'json',
      headers: {}
    }).then((response) => {
      return checkStatus(response)
    })
  },
  postBody(url, data) {
    return axios({
      method: 'POST',
      url,
      data: data,
      timeout: 300000,
      dataType: 'json',
      headers: {
        'Content-Type': 'application/json'
      },
      withCredentials: true
    })
      .then((response) => {
        return checkStatus(response)
      })
      .then((res) => {
        return checkCode(res)
      })
  },
  put(url, data) {
    return axios({
      method: 'PUT',
      url,
      data: data,
      withCredentials: true,
      timeout: 300000,
      dataType: 'json',
      headers: {}
    }).then((response) => {
      return checkStatus(response)
    })
  },
  deletefn(url, data) {
    return axios({
      method: 'delete',
      url,
      data: data,
      withCredentials: true,
      dataType: 'json',
      headers: {},
      timeout: 300000
    }).then((response) => {
      return checkStatus(response)
    })
  }
}
